package com.elm.controller;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.elm.common.ApiResponse;
import com.elm.po.Person;
import com.elm.po.User;
import com.elm.service.PersonService;
@RestController
@RequestMapping("/api")
public class PersonController {

    @Autowired
    private PersonService personService;
    
    @PostMapping("/persons")  
    public ApiResponse<Person> createPerson(@RequestBody Person person) {
    	try {
    		 if (person.getPassword() == null) {
                 person.setPassword("password");
             }
             personService.createPerson(person);
             Person resultPerson = personService.getPersonById(person.getId());
             Person person1 = new Person();
             BeanUtils.copyProperties(resultPerson, person1); 
             return ApiResponse.success( person1);
        } catch (RuntimeException e) {
            return ApiResponse.error("400", e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("500", "系统错误：" + e.getMessage());
        } 
    }
    
    @GetMapping("/persons/{id}")  
    public ApiResponse<Person> getPerson(@PathVariable Integer id) {
    	try {
             return ApiResponse.success( personService.getPersonById(id));
        } catch (RuntimeException e) {
            return ApiResponse.error("400", e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("500", "系统错误：" + e.getMessage());
        } 
    }
    
    @PutMapping("/user")
    public ApiResponse<Person> updateUser(@RequestBody Person person) {
    	try {
    		Person updatedPerson = personService.updatePerson(person);
    		if(updatedPerson==null) {
    			return ApiResponse.error("500", "更新用户信息失败");
    		}
           return ApiResponse.success(updatedPerson);
       } catch (RuntimeException e) {
           return ApiResponse.error("400", e.getMessage());
       } catch (Exception e) {
           return ApiResponse.error("500", "系统错误：" + e.getMessage());
       } 
    }
}